package com.yonyou.trumpchi;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.yonyou.trumpchi.adapter.ServiceAdapter;
import com.yonyou.trumpchi.entity.ServiceInfo;
import com.yonyou.trumpchi.model.ServiceModel;
import com.yonyou.trumpchi.utils.DensityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务器列表
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private SwipeMenuListView mListView;
    private Context mContext;
    //    private String[] mServices;//服务器列表数据
    private Gson gson;
    private ImageView img_service_add;

    private ServiceInfo delInfo = null;
    private int delPosition = -1;

    private List<ServiceInfo> mList = new ArrayList<>();

    private ServiceAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        init();
        auto();
    }

    private void init() {
        gson = new Gson();
        mContext = this;
        initViews();
        initData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mList.clear();
        mAdapter.notifyDataSetChanged();
        List<ServiceInfo> data = ServiceModel.getServiceList(mContext);
        if (data != null) {
            mList.addAll(data);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void createMenu() {
        SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem upDataItem = new SwipeMenuItem(getApplicationContext());
                upDataItem.setBackground(R.color.green);
                upDataItem.setTitle("修改");
                upDataItem.setTitleSize(14);
                upDataItem.setTitleColor(Color.WHITE);
                upDataItem.setWidth(DensityUtils.dp2px(mContext, 50));
                menu.addMenuItem(upDataItem);


                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem.setBackground(R.color.red);
                deleteItem.setTitle("删除");
                deleteItem.setTitleSize(14);
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setWidth(DensityUtils.dp2px(mContext, 50));
                menu.addMenuItem(deleteItem);

            }
        };
        mListView.setMenuCreator(swipeMenuCreator);
    }

    /**
     * 初始化组件
     */
    private void initViews() {
        img_service_add = (ImageView) findViewById(R.id.img_service_add);
        img_service_add.setOnClickListener(this);
        mListView = (SwipeMenuListView) findViewById(R.id.lv_service);
        mAdapter = new ServiceAdapter(mList, getLayoutInflater());
        createMenu();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent it = new Intent(mContext, MainActivity.class);
                it.putExtra("params", mList.get(i));
                startActivity(it);
            }
        });

        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                delInfo = mList.get(position);
                delPosition = position;
                switch (index) {
                    case 1://delete
                        new MaterialDialog.Builder(mContext)
                                .title("提示")
                                .content("确定要删除此服务器吗？")
                                .positiveText("确定")
                                .positiveColor(Color.WHITE)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        String url = delInfo.getUrl();
                                        for (ServiceInfo info : mList) {
                                            if (info.getUrl().equals(delInfo.getUrl())) {
                                                mList.remove(info);
                                                break;
                                            }
                                        }
                                        ServiceModel.del(mContext, url);
                                        mAdapter.notifyDataSetChanged();
                                        dialog.dismiss();
                                    }
                                })
                                .negativeText("取消")
                                .negativeColor(Color.WHITE)
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                        break;
                    case 0://updata
                        Intent it = new Intent(mContext, AddServiceActivity.class);
                        it.putExtra("upDataServiceInfo", delInfo);
                        startActivity(it);
                        break;
                }
                return false;
            }
        });
        mListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        mListView.setAdapter(mAdapter);
    }

    /**
     * 自动登录
     */
    private void auto() {
        for (ServiceInfo info : mList) {
            String isAuto = info.getParams().get(Constants.SP_AUTO);
            String un = info.getParams().get(Constants.SP_USERNAME);
            String psd = info.getParams().get(Constants.SP_PASSWORD);

            if ((!TextUtils.isEmpty(un)) && (!TextUtils.isEmpty(psd)) && (!TextUtils.isEmpty(isAuto)) && "1".equals(isAuto)) {
                Intent it = new Intent(mContext, MainActivity.class);
                it.putExtra("params", info);
                startActivity(it);
                return;
            }
        }
    }

    @Override
    public void onClick(View view) {
        Intent it = new Intent(mContext, AddServiceActivity.class);
        startActivity(it);
    }

    private MaterialDialog delDialog;

    /**
     * 连续点击两次退出程序;
     */
    private long exitTimeMillis = System.currentTimeMillis();

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTimeMillis == 0 || System.currentTimeMillis() - exitTimeMillis > 1000) {
            exitTimeMillis = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
            return;
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());//退出
            System.exit(0);
        }
    }

}
